//
//  LLEditProfileViewController.m
//  LoveLove
//
//  Created by wkf on 2019/3/28.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "LLEditProfileViewController.h"
#import "LLChangeUsernameViewController.h"
#import "UIImageView+WebCache.h"//图片加载
#import "UpImageTools.h"

@interface LLEditProfileViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UINavigationControllerDelegate>
@property (copy, nonatomic) NSArray *titlesArray; //标题数组
@property (copy, nonatomic) UIImage *imgae; //图片
@property (nonatomic,strong) NSString *headImage;
@property (nonatomic,strong) NSString *nickName;
@property (nonatomic,strong) NSString *signature;
@property (nonatomic,strong) NSString *into;
@end

@implementation LLEditProfileViewController

- (void)viewWillAppear:(BOOL)animated {
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
    self.navigationController.delegate = self;

   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //TODO: 页面Disappear 启用
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD dismiss];
    self.titlesArray = @[@"头像",@"昵称",@"介绍自己"];
//    self.myModel = [LLMyModel new];
    self.nickName = self.userInfo.user_name;
    self.headImage = self.userInfo.user_avatar;
    self.signature = self.userInfo.user_follow;
    self.into = self.userInfo.user_info;
    
    [self.tableView reloadData];
}

- (void)configTableView {
    self.needRefresh = NO;
    [super configTableView];
    [self titleView];
    self.titleLabel.text = @"编辑个人资料";
    self.rightButton.hidden = YES;
    self.lineView.hidden = YES;
    self.tableView.mj_h = LLScreenHeight-self.navH;
    self.tableView.top = self.navH;
    self.tableView.backgroundColor = LLWhiteColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titlesArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.row == 0 ? 102 : 64;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *stringSetupTableViewCell = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:stringSetupTableViewCell];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.text = self.titlesArray[indexPath.row];
    cell.textLabel.textColor = LLColorRGB(0);
    cell.textLabel.font = LLRegularFont(17);
    cell.detailTextLabel.textColor = LLColorRGB(235);
    cell.detailTextLabel.font = LLRegularFont(17);
    if (indexPath.row == 0) {
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(LLScreenWidth-100, 11, 80, 80)];
        imageview.layer.masksToBounds = YES;
        LLUserInfo *user = [LLUserInfo sharedUser];
        NSURL *ImagePath1 =[NSURL URLWithString:self.headImage];
        [imageview sd_setImageWithURL:ImagePath1 placeholderImage:[UIImage imageNamed:@"椭圆 1596"]];
        imageview.contentMode = UIViewContentModeScaleAspectFill;
        imageview.layer.cornerRadius = 40;
        [cell addSubview:imageview];
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(15, 101, LLScreenWidth-35, 1)];
        lineview.backgroundColor = LLColorRGB(235);
        [cell addSubview:lineview];
    } else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.row == 1) {
            if ([self.nickName length] == 0) {
                cell.detailTextLabel.text = @"请输入昵称";
            } else {
                cell.detailTextLabel.text = self.nickName;
                cell.detailTextLabel.textColor = LLColorRGB(0);
            }
        } else if (indexPath.row == 2) {
            if ([self.into length] == 0) {
                cell.detailTextLabel.text = @"可以说说你的职业或者爱好";
            } else {
                cell.detailTextLabel.text = self.into;
                cell.detailTextLabel.textColor = LLColorRGB(0);
            }
        } else {
            if ([self.signature length] == 0) {
                cell.detailTextLabel.text = @"请输入签名";
            } else {
                cell.detailTextLabel.text = self.signature;
                cell.detailTextLabel.textColor = LLColorRGB(0);
            }
        }
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(15, 63, LLScreenWidth-35, 1)];
        lineview.backgroundColor = LLColorRGB(235);
        [cell addSubview:lineview];
    }
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, LLScreenWidth, 60)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(30, 8, LLScreenWidth - 60, 44);
    button.backgroundColor = [UIColor redColor];
    button.layer.cornerRadius = 6;
    [button setTitle:@"修改" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(modfiy) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            
        }];
        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self takePhoto];
        }];
        UIAlertAction *picture = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self localPhoto];
        }];
        [alertVc addAction:cancle];
        [alertVc addAction:camera];
        [alertVc addAction:picture];
        [self presentViewController:alertVc animated:YES completion:nil];
    } else  {
        LLChangeUsernameViewController *vc = [LLChangeUsernameViewController new];
        vc.type = indexPath.row;
        WeakSelf(weakSelf);
        vc.changeBlock = ^(NSInteger type, NSString *content) {
            if (type == 1) {
                weakSelf.nickName = content;
            }else if(type == 2){
                weakSelf.into = content;
            }else{
                weakSelf.signature = content;
            }
            [weakSelf.tableView reloadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 本地相簿
- (void)localPhoto{
    if ([CommonTools albumAuthority] == NO) {
        [self showSVProgressHUDInfoWithsStatus:@"您还未打开相册权限~"];
    } else {
        //响应事件
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.navigationBar.barTintColor = LLMainColor;
        imagePicker.navigationBar.tintColor = [UIColor whiteColor];
        // 去除毛玻璃效果（解决iOS11中的照片向上偏移导致被导航栏遮挡的问题）
        imagePicker.navigationBar.translucent = NO;
        [imagePicker.navigationBar setTitleTextAttributes:@{
                                                            NSForegroundColorAttributeName:[UIColor whiteColor],
                                                            NSFontAttributeName:LLRegularFont(19)}];
        [[UIViewController currentViewController] presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark - 照相机
- (void)takePhoto{
    if ([CommonTools canRecordViedo] == NO) {
        [self showSVProgressHUDInfoWithsStatus:@"您还未打开相机权限~"];
    } else {
        //响应事件
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [[UIViewController currentViewController] presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self saveImage:img];
        [UpImageTools upLoadImage:img success:^(NSString * _Nonnull url) {
            self.headImage = url;
            [self.tableView reloadData];
        } failure:^(NSString * _Nonnull _NonnullerrorString) {
            
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 对选取的图片进行处理
- (void)saveImage:(UIImage *)image {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    if([fileManager fileExistsAtPath:imageFilePath]) {
        [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    UIImage *smallImage = image;
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    self.imgae = selfPhoto;
    [self.tableView reloadData];
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
    self.navigationController.delegate = nil;
    [LLNotificationCenter removeObserver:self];
}

-(void)modfiy{
    if (self.signature.length == 0 && self.nickName.length == 0 && self.into.length == 0) {
        [self showSVProgressHUDInfoWithsStatus:@"请输入完整的信息~"];

    }else{
        [self sendModityRequst];
    }
}


#pragma mark---修改请求
-(void)sendModityRequst{
    WeakSelf(weakSelf);
    [self showSVProgressHUD];
    LLUserInfo *user = [LLUserInfo sharedUser];
    
    NSMutableDictionary *muDic = [[NSMutableDictionary alloc]initWithDictionary:@{@"edu_id":@"7",@"user_id":user.user_id,@"user_random":user.user_random}];
    if (self.headImage.length > 0) {
        [muDic setObject:self.headImage forKey:@"user_avatar"];
    }
    if (self.nickName.length > 0) {
         [muDic setObject:self.nickName forKey:@"user_name"];
    }
    if (self.into.length > 0) {
       [muDic setObject:self.into forKey:@"user_info"];
    }
    
    
//        [muDic setObject:self.myModel.signature forKey:@"user_info"];
   

    
    [LLHttpTool post:LLHOST headParams:nil params:muDic success:^(NSDictionary *result) {
       
       
        if ([result[@"code"] integerValue] == 1) {
           [self showSVProgressHUDInfoWithsStatus:@"不能修改，请在30天后修改~"];
            return ;
        }
        
        [self showSVProgressHUDInfoWithsStatus:@"修改成功~"];
        [SVProgressHUD dismissWithDelay:1];
        [self performSelector:@selector(didClickLeftNavAction) withObject:nil afterDelay:1];
        if (self.changeSuccessBlock) {
            self.changeSuccessBlock();
        }
        
    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
